#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

static const int gsockfd = -1;
// static const std::string glocalip= "127.0.0.1";
static const uint16_t glocalport = 8888;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

using server_t = std::function<void(int sockfd, const std::string &message, InetAddr &who)>;
class UdpServer
{
public:
    UdpServer(server_t func, uint16_t localport = glocalport)
        : _sockfd(gsockfd),
          _localport(localport),
          _isrunning(false),
          _func(func)
    {
    }

    ~UdpServer()
    {
    }

    void Init()
    {
        // 1. 创建sock文件
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0) // 失败
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }

        LOG(DEBUG, "create socket succes\n");

        // 2. bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local)); // 使用前最好清空一下

        local.sin_family = AF_INET;
        local.sin_port = htons(_localport); // 注意不要忘了转换网络字节序
        // local.sin_addr.s_addr = inet_addr(_localip.c_str()); // 1.字符串转为4字节整数 2.转换为网络字节序
        local.sin_addr.s_addr = INADDR_ANY; // 服务端与任意IP进行绑定

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0) // 失败
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind sucess!\n");
    }

    void Start()
    {
        _isrunning = true;
        char buffer[1024];

        // 服务器一直运行
        while (1)
        {
            // 1.接收
            struct sockaddr_in peer; // 发送端的信息，例如 ip，端口
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // 接收成功
                buffer[n] = 0;
                InetAddr addr(peer);

                // 执行回调函数，转发消息
                _func(_sockfd, buffer, addr);
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
            }
        }
    }

private:
    int _sockfd;
    // std::string _localip;
    uint16_t _localport;
    bool _isrunning;

    server_t _func;
};